package template

import (
	"lao-a/helper"
	"lao-a/models/h5"
	"lao-a/models/model"

	"github.com/yl10/kit/orm"
)

// DAO 当前数据库操作对象
type DAO struct {
	ctx *helper.Context
	db  *orm.XormPlus
}

// NewDAO 初始化DAO
func NewDAO(ctx *helper.Context) *DAO {
	return &DAO{
		ctx: ctx,
		db:  ctx.GetDB(),
	}
}

//GetTemplates 获取模板字典
func (m *DAO) GetTemplates(typeID string) ([]model.TdTemplate, error) {
	var tpls []model.TdTemplate
	var err error
	if typeID == "" || typeID == "All" {
		err = m.db.Where("status=1").Find(&tpls)
	} else {
		err = m.db.Where("type_id=?", typeID).And("status=1").Find(&tpls)
	}
	return tpls, err
}

//GetTemplatesByPage 分页获取模板字典
func (m *DAO) GetTemplatesByPage(typeID string, Page int, Pagenum int) ([]model.TdTemplate, error) {
	var tpls []model.TdTemplate
	var err error
	if typeID == "" || typeID == "All" {
		err = m.db.Where("status=1").Limit(Pagenum, Page*Pagenum).Find(&tpls)
	} else {
		err = m.db.Where("type_id=?", typeID).And("status=1").Limit(Pagenum, Page*Pagenum).Find(&tpls)
	}
	return tpls, err
}

//Template 模板字典详情
type Template struct {
	model.TdTemplate `xorm:"extends"`
	MotionId         string
	MotionConfig     string
	MusicName        string
	Thumb            string
	MusicDesc        string
	Mp3Url           string
	OggUrl           string
	Modules          []PageTemplate
}

//GetTemplateByID 根据模板ID获取模板字典
func (m *DAO) GetTemplateByID(tplID string) (*Template, error) {
	var tmp []Template
	sql := `SELECT  a.* ,
				b.music_name ,
				b.thumb ,
				b.music_desc ,
				b.mp3_url ,
				b.ogg_url
			FROM    td_template a
				LEFT JOIN ta_object_motions c on a.tpl_id=c.object_id and c.object_type='` + h5.MOTION_TEMPLATE + `'
				LEFT JOIN td_music b ON a.music_id = b.music_id
			WHERE   a.tpl_id = '` + tplID + `'`

	err := m.db.Sql(sql).Find(&tmp)
	if len(tmp) > 0 {
		tmp[0].Modules, err = m.GetPageByTplID(tplID)
		return &tmp[0], err
	}
	return nil, nil
}
